<template>
  <div class="container">
    <!-- 头部 -->
    <img class="head" alt="example" style="width: 100%" :src="titleBackUrl" v-if="this.titleBackUrl != ''"/>
    <!-- 内容 -->
    <div class="content">
      <!-- 左侧图表 -->
      <div class="conLeft">
        <!--         安装信息-->
        <div class="install">
          <!-- 故障日志 -->
          <div class="errorTitle">故障日志</div>
          <!-- 日志列表 -->
          <ul class="errorList">
            <li
              class="errorItem"
              :class="getErrorListClass(item,i)"
              v-for="(item, i) in errorList"
              :key="item.id"
              @click="realTimePlay(item.gatewayCode,item.gatewayChannel)">
              <div class="errorMessage">
                <!--                <p class="errorType">网关编号：{{ item.gatewayCode }}</p>-->
                <p class="errorType">网关名称：{{ item.gatewayName }}</p>
                <p class="errorType">故障类别：{{ getError(item) }}</p>
                <p class="errorTime">时间：{{ item.exceptionTime }}</p>
                <p class="errorGennel"><span>通道：{{ item.gatewayChannel }}</span> <span>分数：{{ item.score }}</span></p>
              </div>
              <div class="playBtn">
                <!-- <img @click.stop="click(item)" src="~@/assets/img/playbtn.png" alt=""> -->
                <div @click.stop="click(item)" class="playButton"></div>
              </div>
            </li>
          </ul>
        </div>
        <!-- 频谱图 -->
        <div class="spectrum">
          <div class="title">音频对比图</div>
          <div>
            <!-- 下拉模型选择 -->
            <div class="chooseModel">
              <div class="model">
                <a-select
                  style="width: 125px"
                  v-model="modelName">
                  <a-select-option
                    v-for="(item,idex) in modelList"
                    :key="idex"
                    :value="item.faultName"
                    @click="getException(item)">{{ item.faultName }}
                  </a-select-option>
                </a-select>
              </div>
              <div class="modelTime">{{ errorTime }}</div>
            </div>
            <div class="wave" id="spectrum">
            </div>
          </div>
          <div class="empty" v-if="isEmptyData">暂无数据</div>
        </div>
      </div>
      <!-- 中部图表 -->
      <div class="conCenter">
        <div class="topology">
          <div class="deviceImg">
            <ImageMarkersView :imageData="imgUrl[0]" :markers="markers" @onMicClick="handleClick" />
          </div>
        </div>
        <div class="quantity">
          <div class="audioTitle">{{ audioTitle }}</div>
          <div class="play" v-show="playing" @click="stop()">暂 停</div>
          <div id="waveform" ref="waveform" v-show="false">
            <!-- Here be the waveform -->
          </div>
          <div class="audioCanvas">
            <canvas
              width="800px"
              height="90px"
              id="canvas"></canvas>
            <a-divider class="myDivider"/>
          </div>
          <div class="vibrationTitle">{{ vibrationTitle }}</div>
          <div id="vibration" v-show="true"></div>
          <div v-show="false" class="emptyData"></div>
        </div>
      </div>
      <!-- 右侧图表 -->
      <div class="conRight">
        <!-- 故障占比图 -->
        <div class="proportion">
          <div class="title">网关温度实时监控</div>
          <div class="tempture">
            <div class="gateway-list">
              <img class="gateway-image" :src="gatewayImgUrl">
              <ul class="my-gateway">
                <li @click="selectGateway = index" :class="{'hover':selectGateway == index}" v-for="(_,index) in gatewayList" :key="index">#{{ index+1 }}</li>
              </ul>
            </div>
            <div class="right">
              <span class="temp-title">网关CPU温度</span>
              <div class="temps">
                <div class="tempnum">
                  <div :class="getChannelClass(currentSelectGateway.temp||0)"></div>
                  <!--                  <div class="temp-route">{{ currentSelectGateway.gatewayCode ||'' }}</div>-->
                  <div class="temp-route">{{ currentSelectGateway.gatewayName ||'' }}</div>
                  <div class="temp-num">{{ Number(currentSelectGateway.temp||0).toFixed(1) }}℃</div>
                </div>
              </div>
            </div>

          </div>
        </div>
        <!-- 得分趋势图 -->
        <div class="scoreCon">
          <div class="title">声纹评估趋势</div>
          <div class="score"></div>
          <div class="xLine"></div>
          <!-- <div class="title">音频对比图</div> -->
        </div>
        <!-- XXXX图 -->
        <div class="chartXXX">
          <div class="title">语谱图</div>
          <div v-show="!isEmptyData" id="container2" ref="container" style="padding: 26px 26px">
          </div>
          <div class="emptyData" v-show="isEmptyData"></div>
          <div class="empty" v-if="isEmptyData">暂无数据</div>
          <div id="container1" ref="container1" v-show="false"></div>
          <div id="wavesurfer" v-show="false"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { STable } from '@/components'
  import * as echarts from 'echarts'
  import colorMap from '@/assets/js/color_map'
  import {
    getFaultModelList,
    getTopology,
    getDeviceDetail,
    involvedDetail,
    getBufferByPath,
    exceptionLogGroupByRouter,
    getCollectTemp,
    getExceptionLately,
    getGatewayChannelNewFile
  } from '@/api/modular/system/indexManage'
  import WaveSurfer from 'wavesurfer.js'
  import SpectrogramPlugin from 'wavesurfer.js/dist/plugin/wavesurfer.spectrogram'
  import { player } from '@/assets/js/mmplayer'
  import { channelTypeList } from '@/api/modular/main/bizchanneltype/bizChannelTypeManage'
  import ImageMarkersView from '@/components/ImageMarkersView/ImageMarkersView'
  import { getBizFaultModel } from '@/api/modular/main/bizfaultmodel/bizFaultModelManage'
  import symbolPic from '@/assets/img/symbol.png'
  import { sysFileInfoDetail } from '@/api/modular/system/fileManage'
  import initTitleImg from '@/assets/img/titlebg_gongye.png'

  let myLine
  const thresholder = 20
  let myChart
  let myVibration

  export default {
    components: {
      STable,
      ImageMarkersView
    },
    data: function () {
      return {
        url: window.CONST.VUE_APP_API_BASE_URL,
        fileUrl: window.CONST.VUE_APP_API_BASE_FILE_URL,
        scoreList: [],
        scoreDiffList: [],
        exceptionlist: [],
        id: 0,
        modelList: [],
        colorMap: colorMap,
        calcSuccess: 0,
        errorTime: '',
        fileName: '',
        ws: null,
        playList: [],
        isPlaying: false,
        mTokenNum: '',
        realTimePlayItem: {},
        errorName: '',
        audioTitle: '音频播放',
        vibrationTitle: '振动信号',
        errorList: [],
        audioName: '',
        intervalList: [],
        errName: '',
        playing: false,
        groupId: 0,
        modelName: '请选择模型',
        leftData: [],
        rightData: [],
        channelTypeList: [],
        animCount: 0,
        clickCount: 0,
        myChartXData: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        myChartYData: [[1, 3, 2, 4, 6, 5, 7, 9, 8, 11, 12, 9]],
        isEmptyData: true,
        imgUrl: [],
        temp: '0',
        markers: [],
        gatewayList: [],
        gatewayImgUrl: '',
        selectGateway: 0,
        autoSelectGatewayTaskId: null,
        dataBar: [],
        dataLine: [],
        timeNow: false,
        wavFileUrl: '',
        titleBackUrl: ''
      }
    },
    watch: {
      url (newValue, oldValue) {
        if (newValue !== oldValue) {
          this.loadUrl(newValue)
        }
      }
    },
    computed: {
      currentSelectGateway () {
        const gateway = this.gatewayList[this.selectGateway]
        const params = {
          gatewayCode: '',
          gatewayName: '',
          temp: ''
        }
        const p = Object.assign(params, gateway)
        if (p.temp === '' || p.temp === 0) {
          p.temp = Math.random() * 10 + 40
        }
        return p
      }
    },
    methods: {
      // 声纹趋势评估图
      initLine () {
        const score = document.querySelector('.score')
        myLine = echarts.init(score, null, { renderer: 'svg' })
      },
      updateLine () {
        const option = {
          grid: {
            top: '18%',
            left: '15%',
            right: '6%',
            bottom: '30%',
            containLabel: false
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['健康趋势'],
            textStyle: {
              color: '#fff',
              fontSize: 12
            },
            right: '20px',
            top: '20px'
          },
          xAxis: [
            {
              show: false,
              // offest: 100,
              // onZero: false,
              type: 'category',
              axisLine: {
                lineStyle: {
                  color: '#ccc'
                }
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              splitLine: {
                show: false,
                lineStyle: {
                  color: '#164a72',
                  interval: 1
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#ccc'
                }
              }
            }
          ],
          series: [
            {
              name: '健康趋势',
              showAllSymbol: false,
              symbol: `image://${symbolPic}`,
              symbolSize: 0,
              type: 'line',
              data: this.scoreList,
              lineStyle: {
                color: '#ff7933',
                width: 1
              }

            }
          ]
        }
        option && myLine.setOption(option)
        window.addEventListener('resize', () => {
          myLine.resize()
        })
      },
      // 音频对比图
      initCharts () {
        const chartDom = document.getElementById('spectrum')
        myChart = echarts.init(chartDom, null, { renderer: 'svg' })
      },
      upadateCharts () {
        const option = {
          title: {
            text: ' 当前故障对比图',
            show: false
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            top: '10%',
            textStyle: { // 图例文字的样式
              color: '#fff',
              fontSize: 10
            },
            axisLabel: {
              textStyle: {
                color: '#fff'
              }
            },
            show: true,
            data: ['检材', '模型']
          },
          grid: {
            top: '30%',
            left: '10%',
            right: '10%',
            bottom: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.myChartXData,
            axisLabel: {
              show: false,
              textStyle: {
                color: 'none'
              }
            },
            axisLine: {
              show: true,
              color: '#fff',
              lineStyle: {
                show: false,
                color: '#a1a1a1'
              }
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: '#164a72'
              },
              interval: 1
            }
          },
          yAxis: [{
            color: '#fff',
            type: 'value',
            axisLine: {
              show: true,
              color: '#fff',
              lineStyle: {
                color: '#a1a1a1'
              }
            },
            axisLabel: {
              show: true,
              color: '#fff'
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: '#164a72',
                interval: 1
              }
            }
          }],
          series: [
            {
              name: '检材',
              type: 'line',
              smooth: true,
              data: this.myChartYData[0]
            },
            {
              name: '模型',
              type: 'line',
              smooth: true,
              data: this.myChartYData[1]
            }
          ]
        }
        option && myChart.setOption(option)
        myChart.resize()
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      },
      // 振动信号图
      initVibration () {
        const vibration = document.getElementById('vibration')
        myVibration = echarts.init(vibration, null, { renderer: 'svg' })
      },
      updateVibration () {
        const xDates = []
        const yDates = []
        for (let i = 0; i < 1000; i++) {
          xDates.push(i)
          yDates.push(Math.random() * 100)
        }
        const option = {
          title: {
            text: '',
            top: '4px',
            right: '10px',
            textStyle: {
              color: '#66E9F9',
              fontSize: '16px'
            }
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
            top: '20%'
          },
          xAxis: {
            type: 'category',
            data: xDates,
            boundaryGap: false, // 显示在两个刻度线中间
            axisTick: {
              show: false // 刻度线
            },
            splitLine: {
              show: false
            },
            axisLine: {
              show: false,
              color: '#fff',
              lineStyle: {
                show: false,
                color: '#a1a1a1'
              }
            },
            axisLabel: {
              show: false,
              textStyle: {
                color: 'none'
              }
            }
          },
          yAxis: {
            type: 'value',
            splitLine: {
              show: false
            },
            axisLine: {
              show: false,
              color: '#fff',
              lineStyle: {
                color: '#a1a1a1'
              }
            },
            axisLabel: {
              show: false,
              color: '#fff'
            }
          },
          series: [
            {
              data: yDates,
              type: 'line',
              symbol: 'none',
              lineStyle: {
                color: '#EC9079',
                width: 1
              }
            }
          ]
        }
        option && myVibration.setOption(option)
        myVibration.resize()
        window.addEventListener('resize', function () {
          myVibration.resize()
        })
      },
      onFFtChnaged (type, buffer) {
        const delta = 8000 / buffer.length
        const xData = []
        for (const i in buffer) {
          xData.push(parseInt(delta * i))
          buffer[i] = parseInt((buffer[i] / 255) * 100)
        }
        this.myChartXData = xData
        if (type === '0') {
          this.myChartYData[0] = buffer
          this.calc(type, buffer)
        } else if (type === '1') {
          this.myChartYData[1] = buffer
          this.calc(type, buffer)
        }
        this.$nextTick(() => {
          this.upadateCharts()
        })
      },
      calcWave (type, buffer) {
        const row = buffer.length
        const col = buffer[0].length
        const mergeAvg = []
        for (let i = 0; i < col; i++) {
          let ampCount = 0
          for (let j = 0; j < row; j++) {
            ampCount += buffer[j][i]
          }
          mergeAvg.push(ampCount / row)
        }
        this.onFFtChnaged(type, mergeAvg)
      },
      loadUrl (url) {
        this.getWaveBuffer(url, this.setWaveBuffer)
      },
      setWaveBuffer (buff) {
        this.wavesurfer.empty()
        this.wavesurfer.loadArrayBuffer(buff)
      },
      calc (type, buffer) {
        let lowHz = -1
        let highHz = -1
        this.calcSuccess += 1
        for (let i = 0; i < buffer.length; i++) {
          if (buffer[i] > thresholder && lowHz === -1) {
            lowHz = i
          }
          if (lowHz !== -1 && highHz === -1 && buffer[i] < thresholder) {
            highHz = i - 1
            break
          }
        }
      },
      // 获取分数列表
      getscoreList (id) {
        const that = this
        that.initLine()
        that.getUploadScoreListById(id)
      },
      getUploadScoreListById (id) {
        const that = this
        getExceptionLately({ deviceId: id }).then((res) => {
          if (res.success) {
            const arr = []
            for (let i = 0; i < res.data.length; i++) {
              arr.push(res.data[i])
            }
            that.scoreList = arr
            that.updateLine()
          }
        })
      },
      back () {
        this.$router.push({ name: 'Console' })
      },
      paly () {
        player._loadSound(this.wavFileUrl, 'keepAlive')
      },
      // 获取故障模型列表
      getFaultModelList () {
        const that = this
        getDeviceDetail({ id: that.id }).then(res => {
          if (res.success) {
            involvedDetail({ id: res.data.industryId }).then(res => {
              if (res.success) {
                that.groupId = res.data.groupId
                const formData = new FormData()
                formData.append('groupId', res.data.groupId)
                getFaultModelList(formData).then(res => {
                  that.modelList = res.data
                  // 初始化故障日志
                  that.initExceptLog()
                  const timer = setInterval(function () {
                    that.initExceptLog()
                  }, 15000)
                  that.intervalList.push(timer)
                })
              }
            })
          }
        })
      },
      // 选择故障模型后的操作
      getException (item) {
        const that = this
        const modelFileName = item.modelFile.split(',')
        that.wavesurfer.load(this.url + '/' + modelFileName[0])
        const formData = new FormData()
        formData.append('fileName', '/' + modelFileName[0])
        getBufferByPath(formData).then(res => {
          if (res.success) {
            that.calcWave('1', res.data[0].data)
          }
        })
      },
      getTopologyList () {
        const that = this
        getTopology({ deviceId: that.id }).then(res => {
          if (res.success) {
            if (res.data.id === 'deviceIdnull') {
              return
            }
            if (res.data.device) {
              const device = res.data.device
              that.changeTitle(device.deviceName, device.titleFilePath)
            }
            that.imgUrl[0] = that.url + res.data['background-image']
            that.normalImgUrl = that.url + res.data['background-image']
            if (res.data.children) {
              that.gatewayList = res.data.children
              if (that.gatewayList.length > 0) {
                try {
                  this.gatewayImgUrl = require('@/assets/devices/' + that.gatewayList[0].typeCode + '.png')
                } catch (e) {
                  console.log(e)
                }
                if (that.gatewayList[0].children.length > 0) {
                  that.realTimePlay(that.gatewayList[0].gatewayCode, that.gatewayList[0].children[0].channel)
                }
              }
              that.getCpuTemp()
              const timer = setInterval(() => {
                that.getCpuTemp()
              }, 15000)
              that.intervalList.push(timer)
            }
          }
        })
      },
      initWave () {
        const that = this
        that.wavesurfer = WaveSurfer.create({
          container: that.$refs.waveform,
          scrollParent: true,
          plugins: [
            SpectrogramPlugin.create({
              container: '#container2',
              labels: true,
              colorMap: that.colorMap,
              deferInit: false, // 延迟初始化， that.wavesurfer.initPlugin('spectrogram')初始化
              pixelRatio: 1.3,
              fftSamples: 512,
              sampleRate: 16000,
              noverlap: 64,
              windowFunc: 'hann'
            })
          ]
        })
      },
      // 点击故障日志播放按钮
      click (item) {
        const that = this
        that.errName = item.errorName
        that.audioName = item.fileName
        if (item.fileName) {
          that.toContrastDetail()
        } else {
          that.$message.error('该通道无故障文件')
        }
      },
      // 跳转故障详情
      toContrastDetail () {
        const that = this
        that.$router.push({
          path: '/contrastDetail', query: { fileUrl: this.audioName, errName: this.errName, groupId: that.groupId }
        })
      },
      stop () {
        if (player.source) {
          player.source.onended = null
          player.stop()
          this.playing = false
        }
      },
      initExceptLog () {
        const that = this
        exceptionLogGroupByRouter({ deviceId: that.id }).then(res => {
          if (res.success) {
            const tmp = JSON.parse(JSON.stringify(res.data))
            // 为了后面的动效
            for (let i = 0; i < tmp.length; i++) {
              tmp[i].isDelete = 1
            }
            // 为了后面的动效
            for (let i = 0; i < res.data.length; i++) {
              tmp.unshift({
                id: ++that.animCount,
                gatewayCode: res.data[i].gatewayCode,
                gatewayName: res.data[i].gatewayName,
                errorName: res.data[i].errorName,
                exceptionTime: res.data[i].exceptionTime,
                fileName: res.data[i].fileName,
                gatewayChannel: res.data[i].gatewayChannel,
                status: res.data[i].status,
                xposion: res.data[i].xposion,
                yposion: res.data[i].yposion,
                score: res.data[i].score,
                gatewayId: res.data[i].gatewayId,
                model: res.data[i].model,
                isDelete: 0
              })
            }
            if (tmp.length > 0) {
              const eName = tmp[tmp.length - 1].errorName
              if (eName !== '初始未知故障' && eName !== '未知故障' && eName !== '正常') {
                getBizFaultModel({ faultName: eName }).then(res => {
                  if (res.success && res.data) {
                    if (res.data.faultGif) {
                      this.imgUrl[0] = this.fileUrl + res.data.faultGif
                    }
                  }
                })
              } else {
                this.imgUrl[0] = that.normalImgUrl
              }
            }
            that.errorList = tmp
            setTimeout(() => {
              const newTmp = []
              const markers = []
              const tmp = that.errorList
              for (const item of tmp) {
                if (item.isDelete === 0) {
                  newTmp.push(item)
                  let url = ''
                  if (item.model === 'ZKHY-IVOD-007') {
                    url = 'mic-dip'
                  } else if (item.model === 'ZKHY-AWG-001' || item.model === 'ZKHY-AWG-002') {
                    url = 'mic-sonic-source'
                  } else if (item.status === 0) {
                    url = 'mic-offline'
                  } else if (item.errorName) {
                    if (item.errorName === '正常') {
                      url = 'mic-normal'
                    } else if (item.errorName === '初始未知故障' || item.errorName === '未知故障') {
                      url = 'mic-error'
                    } else {
                      // 这里为什么又和modelList有关系
                      for (let j = 0; j < this.modelList.length; j++) {
                        if (item.errorName === this.modelList[j].faultName) {
                          if (this.modelList[j].faultLevel === 'height' || this.modelList[j].faultLevel === 'middle') {
                            url = 'mic-error'
                          } else {
                            url = 'mic-warn'
                          }
                          break
                        } else if (item.errorName === '初始未知故障' || item.errorName === '未知故障') {
                          url = 'mic-error'
                          break
                        }
                      }
                      if (!url) {
                        url = 'mic-error'
                      }
                    }
                  } else {
                    url = 'mic-normal'
                  }
                  const temp = (Math.random() * (60 - 40 + 1) + 40).toString().slice(0, 2)
                  const param = {
                    url: url,
                    x: item.xposion + '%',
                    y: item.yposion + '%',
                    id: item.id,
                    gatewayCode: item.gatewayCode,
                    gatewayName: item.gatewayName,
                    channel: item.gatewayChannel,
                    temp: temp
                  }
                  markers.push(param)
                }
              }
              that.errorList = newTmp
              that.markers = markers
            }, 500)
            that.animCount = that.animCount % 1000
          }
        })
      },
      getError (item) {
        if (item.model === 'ZKHY-IVOD-007' || item.model === 'ZKHY-AWG-002' || item.model === 'ZKHY-AWG-001') {
          return '正常'
        }
        if (item.status === 0) {
          return '离线'
        } else if (item.status === 1) {
          return item.errorName || '正常'
        } else {
          return item.errorName
        }
      },
      getErrorListClass (item, i) {
        const classes = []
        if (i === 0) {
          classes.push('animIn')
        }
        if (item.isDelete === 1) {
          classes.push('animOut')
        }
        if (item.status === 0 && item.model !== 'ZKHY-IVOD-007' && item.model !== 'ZKHY-AWG-002' && item.model !== 'ZKHY-AWG-001') {
          classes.push('offline')
        } else {
          if (item.errorName) {
            if (item.errorName === '正常') {
              classes.push('normally')
            } else if (item.errorName === '初始未知故障' || item.errorName === '未知故障') {
              classes.push('error')
            } else {
              for (let j = 0; j < this.modelList.length; j++) {
                if (item.errorName === this.modelList[j].faultName) {
                  if (this.modelList[j].faultLevel === 'height' || this.modelList[j].faultLevel === 'middle') {
                    classes.push('error')
                  } else {
                    classes.push('error1')
                  }
                  return classes
                } else if (item.errorName === '初始未知故障' || item.errorName === '未知故障') {
                  classes.push('error')
                  break
                }
              }

              if (classes.length === 0) {
                classes.push('error')
              }
            }
          } else {
            classes.push('normally')
          }
        }
        return classes
      },
      // 实时流播放
      realTimePlay (gatewayCode, gatewayChannel) {
        const that = this
        that.clickCount++
        if (that.clickCount > 1) {
          that.$message.warn('请勿频繁点击')
          return
        }
        setTimeout(() => {
          that.clickCount = 0
        }, 1000)
        const param = {
          gatewayCode: gatewayCode,
          channel: gatewayChannel
        }
        that.realTimePlayItem = param
        if (player.source) {
          player.stop()
          player.source.onended = null
        }
        that.getChannelNewFile(param)
      },
      getChannelNewFile (param) {
        const that = this
        getGatewayChannelNewFile(param).then(res => {
          if (res.success) {
            if (res.data && res.data.fileId) {
              sysFileInfoDetail({ id: res.data.fileId }).then(res => {
                if (res.success) {
                  that.playing = true
                  that.audioTitle = '实时流播放: ' + param.channel + '通道'
                  that.wavFileUrl = window.CONST.VUE_APP_API_BASE_FILE_URL + res.data.fileBucket + '/' + res.data.fileObjectName
                  that.paly()
                  that.wavesurfer.load(that.wavFileUrl)
                  const formData = new FormData()
                  formData.append('fileName', '/' + res.data.fileBucket + '/' + res.data.fileObjectName)
                  getBufferByPath(formData).then(res => {
                    if (res.success) {
                      that.isEmptyData = false
                      that.isEmptyData = false
                      that.calcWave('0', res.data[0].data)
                    }
                  })
                }
              })
            } else {
              that.$message.warn('暂无文件')
            }
          }
        })
      },
      getChannelTypeList () {
        channelTypeList().then(res => {
          if (res.success) {
            this.channelTypeList = res.data
          }
        })
      },
      // 获取网关CPU温度
      getCpuTemp () {
        const that = this
        for (let i = 0; i < that.gatewayList.length; i++) {
          const form = new FormData()
          form.append('deviceCode', that.gatewayList[i].gatewayCode)
          getCollectTemp(form).then(res => {
            if (res.success && res.data !== null) {
              that.gatewayList[i].temp = res.data
            } else {
              that.gatewayList[i].temp = 0
            }
          })
        }
      },
      getChannelClass (temp) {
        if (temp <= 45) {
          return 'tempture-low'
        } else if (temp > 45 && temp <= 50) {
          return 'tempture-middle-50'
        } else if (temp > 50 && temp <= 65) {
          return 'tempture-middle-65'
        } else {
          return 'tempture-high'
        }
      },
      // 模拟自动切换网关通道数
      autoSwitchGateway () {
        this.autoSelectGatewayTaskId = setInterval(() => {
          this.selectGateway = ((this.selectGateway + 1) % this.gatewayList.length)
        }, 3000)
      },

      handleClick (marker) {
        this.realTimePlay(marker.gatewayCode, marker.channel)
      },
      changeTitle (deviceName, titleFilePath) {
        // 上传了头部图片 使用上传的
        // 未上传使用默认的
        if (titleFilePath) {
          this.titleBackUrl = this.fileUrl + titleFilePath;
        } else {
          this.titleBackUrl = initTitleImg
        }

        // switch (deviceName) {
        //   case '中科昊音变压器':
        //     document.getElementById('head').classList.add('headTitle-gongye')
        //     break
        //   case '3#往复泵（樊一注水站）':
        //     document.getElementById('head').classList.add('headTitle-wangfubeng')
        //     break
        //   case '63#抽油机':
        //     document.getElementById('head').classList.add('headTitle-chouyouji')
        //     break
        //   case '一号风机叶片':
        //     document.getElementById('head').classList.add('headTitle-fengye')
        //     break
        //   case '一号风机主轴':
        //     document.getElementById('head').classList.add('headTitle-zhuzhou')
        //     break
        //   case '水轮发电机组':
        //     document.getElementById('head').classList.add('headTitle-shuilun')
        //     break
        //   case '石油管道':
        //     document.getElementById('head').classList.add('headTitle-shiyou')
        //     break
        //   case '山东东营铁塔':
        //   document.getElementById('head').classList.add('headTitle-tieta')
        //   break
        // }
      }
    },
    created () {
      const that = this
      that.id = that.$route.query.id
      player.ini()
      that.getChannelTypeList()
      that.getFaultModelList()
    },
    destroyed () {
      if (this.ws) {
        this.ws.close()
      }
      window.eventBus.$off('stop')
      this.wavesurfer.empty()
      for (let i = 0; i < this.intervalList.length; i++) {
        clearInterval(this.intervalList[i])
      }
      if (player.source) {
        player.source.onended = null
        player.stop()
        this.playing = false
      }

      // 清空自动切换网关选项卡
      if (this.autoSelectGatewayTaskId) {
        clearInterval(this.autoSelectGatewayTaskId)
      }
    },
    mounted () {
      const that = this
      if (that.id !== 0) {
        that.getscoreList(that.id)
        that.initWave()
        that.initCharts()
        that.upadateCharts()
        that.getTopologyList(that.id)
        // 振动
        that.initVibration()
        that.updateVibration()
        window.eventBus.$on('stop', msg => {
          if (msg === 'stop') {
            that.playing = false
            player.ini()
            that.realTimePlay(that.realTimePlayItem.gatewayCode, that.realTimePlayItem.channel)
          }
        })
        // 新增10/11 自动切换网关选项卡
        this.autoSwitchGateway()
      }
    }
  }
</script>
<style scoped="scoped" lang="scss">
  @import "../../../assets/scss/detail.scss";

  .headTitle-fengye{
    background-image: url('../../../assets/img/titlebg_fengye.png') !important;
  }

  .headTitle-chouyouji{
    background-image: url('../../../assets/img/titlebg_chouyouji.png') !important;
  }

  .headTitle-chitan{
    background-image: url('../../../assets/img/titlebg_chitan.png') !important;
  }

  .headTitle-shengzhen{
    background-image: url('../../../assets/img/titlebg_shengzhen.png') !important;
  }

  .headTitle-wangfubeng{
    background-image: url('../../../assets/img/titlebg_wangfubeng.png') !important;
  }

  .headTitle-zhuzhou{
    background-image: url('../../../assets/img/titlebg_zhuzhou.png') !important;
  }

  .headTitle-gongye{
    background-image: url('../../../assets/img/titlebg_gongye.png') !important;
  }

  .headTitle-shiyou{
    background-image: url('../../../assets/img/titlebg_shiyouguandao.png') !important;
  }

  .headTitle-shuilun{
    background-image: url('../../../assets/img/titlebg_shuilunfadian.png') !important;
  }

</style>
